  class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  # before_filter :login_required
  helper_method :current_user, :current_store, :current_customer

  def current_user
    @current_user ||= StoreStaff.find_by(id: session[:user_id])
  end

  def current_store
    @current_store ||= current_user.store
    raise ActiveRecord::RecordNotFound.new unless @current_store
    @current_store
  end

  def signed_in?
    current_user.present?
  end

  def current_admin
    @current_admin ||= Staffer.find_by(id: session[:admin_id])
  end

  def current_customer
    @current_customer ||= StoreCustomer.find_by(id: session[:customer_id])
  end

  def current_cart
    @cart ||= Cart.find_or_create_by(store_id: @normal_store_id, store_customer_id: current_customer.id)
    # @cart ||= Cart.find_or_create_by(id: session[:cart_id])
  end

  def decode(params)
    Base64.decode64(params)
  end

  def encode(params)
    Base64.encode64(params)
  end

  private
  def login_required
    # @current_user = Staffer.first if Rails.env.development? || true
    redirect_to new_session_path unless current_user.present?
  end

  def admin_required
    redirect_to new_admin_session_path unless current_admin.present?
  end

  def customer_required
     unless current_customer.present?
       session[:redirect_to] = request.referer
       redirect_to new_sales_session_path(store_id: encode(params[:store_id])), notice: '操作前请先进行登陆!'
     end
  end

end
